package com.sanben.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author cyh
 * @description: 中文转英文字母
 * @date: 2020-08-11
 */
public class ChineseUtil {

    /**
     * 将汉字转成拼音(取首字母或全拼)
     *
     * @param ChineseCharacter
     * @param full 是否全拼
     * @return
     */
    public static String convertPinyin(String ChineseCharacter, boolean full) {
        String regExp = "^[\u4E00-\u9FFF]+$";
        StringBuffer sb = new StringBuffer();
        if (ChineseCharacter == null || "".equals(ChineseCharacter.trim())) {
            return "";
        }
        String pinyin = "";
        for (int i = 0; i < ChineseCharacter.length(); i++) {
            char unit = ChineseCharacter.charAt(i);
            if (match(String.valueOf(unit), regExp)) {
                pinyin = convertSinglePinyin(unit);
                if (full) {
                    sb.append(pinyin);
                } else {
                    sb.append(pinyin.charAt(0));
                }
            } else {
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 将单个汉字转成拼音
     *
     * @param ChineseCharacter
     * @return
     */
    private static String convertSinglePinyin(char ChineseCharacter) {
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        String[] res;
        StringBuffer sb = new StringBuffer();
        try {
            //对于多音字，只用第一个拼音
            res = PinyinHelper.toHanyuPinyinStringArray(ChineseCharacter, outputFormat);
            sb.append(res[0]);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return sb.toString();
    }

    /**
     * 将某个字符串的首字母 大写
     *
     * @param str
     * @return
     */
    public static String convertInitialToUpperCase(String str) {
        if (str == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            char ch = arr[i];
            if (i == 0) {
                sb.append(String.valueOf(ch).toUpperCase());
            } else {
                sb.append(ch);
            }
        }

        return sb.toString();
    }

    /***
     * @param str 源字符串
     * @param regex 正则表达式
     * @return 是否匹配
     */
    public static boolean match(String str, String regex) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }
}